package com.leantech.android.browser.dialog

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.leantech.android.browser.databinding.ItemCheckboxBinding
import com.leantech.android.browser.utils.onThrottleClick

class CheckboxAdapter(private val onCheckedChange: (CheckboxBottomSheet.CheckboxItem, Boolean) -> Unit) :
    ListAdapter<CheckboxBottomSheet.CheckboxItem, CheckboxAdapter.CheckBoxItemViewHolder>(
        diffCallback
    ) {

    companion object {
        private val diffCallback =
            object : DiffUtil.ItemCallback<CheckboxBottomSheet.CheckboxItem>() {
                override fun areItemsTheSame(
                    oldItem: CheckboxBottomSheet.CheckboxItem,
                    newItem: CheckboxBottomSheet.CheckboxItem
                ): Boolean {
                    return oldItem.text == newItem.text
                }

                override fun areContentsTheSame(
                    oldItem: CheckboxBottomSheet.CheckboxItem,
                    newItem: CheckboxBottomSheet.CheckboxItem
                ): Boolean {
                    return oldItem == newItem
                }
            }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CheckBoxItemViewHolder {
        val binding =
            ItemCheckboxBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CheckBoxItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CheckBoxItemViewHolder, position: Int) {
        holder.bind(getItem(position), onCheckedChange)
    }

    class CheckBoxItemViewHolder(private val binding: ItemCheckboxBinding) :
        ViewHolder(binding.root) {

        fun bind(
            data: CheckboxBottomSheet.CheckboxItem,
            onCheckedChange: (CheckboxBottomSheet.CheckboxItem, Boolean) -> Unit
        ) {
            binding.root.onThrottleClick {
                binding.checkbox.toggle()
            }

            binding.checkbox.isChecked = data.checked
            binding.checkbox.text = data.text
            binding.checkbox.setOnCheckedChangeListener { buttonView, isChecked ->
                onCheckedChange(data, isChecked)
            }
        }

    }
}